<?php

namespace app\admin\logic;

use support\Exception\ApiException;
use support\Service\LevelService;
use xy_jx\Utils\Excel;

class LevelLogic extends BaseLogic
{


    public static function getList()
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['name']) && $param['name']) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = LevelService::getListPage($where, ['*'], ['id' => 'desc'], [], request()->get('limit', 10));
        return message($list);
    }

    /**
     * 获取职级列表
     * @return array
     * @since 2020/11/20
     */
    public static function getLevelList()
    {
        $list = LevelService::getLevelList();
        return message($list);
    }

    public static function edit()
    {

        $data = request()->post();
        $id = $data['id'] ?? 0;
        if (!isset($data['name']) || empty($data['name'])) {
            throw new ApiException('请输入职位名称');
        }
        if (!isset($data['sort']) || empty($data['sort'])) {
            throw new ApiException('请输入排序');
        }
        $save['name'] = trim($data['name']);
        $save['sort'] = $data['sort'];
        $save['status'] = $data['status'] ?? 1;
        unset($data['id']);
        if ($id == 0) {
            LevelService::add($save);
        } else {
            LevelService::save($save, $id);
        }
        return message();

    }

    public static function delete()
    {
        $ids = request()->post('id');
        if (!$ids) throw new ApiException('记录ID不能为空');
        if (!is_array($ids)) {
            $ids = [$ids];
        }
        LevelService::delete($ids);
        return message();
    }

    public static function status()
    {
        $id = request()->post('id');
        $status = request()->post('status');
        if (!$id) throw new ApiException('记录ID不能为空');
        if (!in_array($status, [1, 2])) throw new ApiException('状态错误');
        LevelService::save(['status' => $status], $id);
        return message();
    }

    public static function exportExcel()
    {
        $param = request()->get();
        $where[] = ["mark", '=', 1];
        if (isset($param['name']) && $param['name']) {
            $where[] = ["name", 'like', "%{$param['name']}%"];
        }
        $list = LevelService::getList($where);
        Excel::header('职级管理', ['id' => '职级ID', 'name' => '职级名称', 'status' => '职级状态', 'sort' => '职级排序'])
            ->content($list)->save('Xlsx', false, '职级管理.xlsx');
        var_dump();
    }

}
